import { useAuthStore } from '@/stores'

interface DialogOptions {
  title: string
  type: string
  content: string
  confirm: () => void
  cancel: () => void
}

interface Window {
  $message?: {
    success: (message: string) => void
    error: (message: string) => void
  }
  $dialog?: {
    confirm: (options: DialogOptions) => void
  }
}

declare global {
  interface Window extends Window {}
}

let isConfirming = false

export function resolveResError(
  code: number,
  message: string,
  needTip: boolean = true
): string | false {
  const authStore = useAuthStore()

  switch (code) {
    case 401:
      if (isConfirming || !needTip) return false
      isConfirming = true
      window.$dialog?.confirm({
        title: '提示',
        type: 'info',
        content: '登录已过期，是否重新登录？',
        onfirm() {
          authStore.logout()
          window.$message?.success('已退出登录')
          isConfirming = false
        },
        cancel() {
          isConfirming = false
        }
      })
      return false
    case 11007:
    case 11008:
      if (isConfirming || !needTip) return false
      isConfirming = true
      window.$dialog?.confirm({
        title: '提示',
        type: 'info',
        content: `${message}，是否重新登录？`,
        onfirm() {
          authStore.logout()
          window.$message?.success('已退出登录')
          isConfirming = false
        },
        cancel() {
          isConfirming = false
        }
      })
      return false
    case 403:
      message = '请求被拒绝'
      break
    case 404:
      message = '请求资源或接口不存在'
      break
    case 500:
      message = '服务器发生异常'
      break
    default:
      message = message ?? `【${code}】: 未知异常!`
      break
  }
  if (needTip) {
    window.$message?.error(message)
  }
  return message
}
